package com.hello.system.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hello.common.log.annotation.Log;
import com.hello.common.log.enums.BusinessType;
import com.hello.common.security.annotation.RequiresPermissions;
import com.hello.system.domain.RentalDeviceCategories;
import com.hello.system.service.IRentalDeviceCategoriesService;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.core.utils.poi.ExcelUtil;
import com.hello.common.core.web.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 设备分类Controller
 * 
 * @author hello
 * @date 2025-07-20
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/categories")
public class RentalDeviceCategoriesController extends BaseController
{
    private final IRentalDeviceCategoriesService rentalDeviceCategoriesService;

    /**
     * 查询设备分类列表
     */
    //@RequiresPermissions("system:categories:list") 
    @GetMapping("/list")
    public TableDataInfo list(RentalDeviceCategories rentalDeviceCategories)
    {
        log.info("======== 查询设备分类列表请求 ========");
        log.info("请求参数: {}", rentalDeviceCategories);
        
        // 获取所有分类数据
        List<RentalDeviceCategories> allList = rentalDeviceCategoriesService.selectRentalDeviceCategoriesList(rentalDeviceCategories);
        
        // 构建树形结构
        List<RentalDeviceCategories> treeList = buildTree(allList, 0L);
        
        // 创建返回结果
        TableDataInfo result = new TableDataInfo();
        result.setRows(treeList);
        result.setTotal(allList.size());
        result.setCode(200);
        result.setMsg("查询成功");
        
        log.info("查询结果: 总记录数={}, 树形数据量={}", allList.size(), treeList.size());
        log.info("======== 查询设备分类列表完成 ========");
        
        return result;
    }
    
    /**
     * 构建树形结构
     */
    private List<RentalDeviceCategories> buildTree(List<RentalDeviceCategories> allList, Long parentId) {
        // 只在顶级调用时打印日志
        if (parentId == 0L) {
            log.info("开始构建分类树结构 - 总数据量: {}", allList.size());
        }
        
        List<RentalDeviceCategories> treeList = new java.util.ArrayList<>();
        
        for (RentalDeviceCategories category : allList) {
            // 处理父ID为null或0的情况
            Long categoryParentId = category.getParentId();
            boolean isMatch = false;
            
            if (parentId == 0L) {
                // 查找顶级分类（父ID为null或0）
                isMatch = (categoryParentId == null || categoryParentId == 0L);
            } else {
                // 查找指定父ID的子分类
                isMatch = parentId.equals(categoryParentId);
            }
            
            if (isMatch) {
                // 递归查找子节点
                List<RentalDeviceCategories> children = buildTree(allList, category.getCategoryId());
                
                // 确保 children始终是一个有效的列表，即使为空
                if (children == null) {
                    children = new java.util.ArrayList<>();
                }
                category.setChildren(children);
                category.setHasChildren(!children.isEmpty());
                
                treeList.add(category);
            }
        }
        
        // 只在顶级调用时打印完成日志
        if (parentId == 0L) {
            log.info("分类树结构构建完成 - 顶级分类数量: {}", treeList.size());
        }
        
        return treeList;
    }

    /**
     * 导出设备分类列表
     */
    //@RequiresPermissions("system:categories:export")
    @Log(title = "设备分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RentalDeviceCategories rentalDeviceCategories)
    {
        log.info("======== 导出设备分类数据请求 ========");
        log.info("导出条件: {}", rentalDeviceCategories);
        
        List<RentalDeviceCategories> list = rentalDeviceCategoriesService.selectRentalDeviceCategoriesList(rentalDeviceCategories);
        log.info("导出数据量: {} 条记录", list.size());
        
        ExcelUtil<RentalDeviceCategories> util = new ExcelUtil<RentalDeviceCategories>(RentalDeviceCategories.class);
        util.exportExcel(response, list, "设备分类数据");
        
        log.info("======== 设备分类数据导出完成 ========");
    }

    /**
     * 获取设备分类详细信息
     */
    //@RequiresPermissions("system:categories:query")
    @GetMapping(value = "/{categoryId}")
    public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
    {
        log.info("======== 获取设备分类详情请求 ========");
        log.info("分类ID: {}", categoryId);
        
        RentalDeviceCategories category = rentalDeviceCategoriesService.selectRentalDeviceCategoriesByCategoryId(categoryId);
        log.info("查询结果: {}", category != null ? "找到分类信息" : "未找到对应分类");
        
        log.info("======== 获取设备分类详情完成 ========");
        return success(category);
    }

    /**
     * 新增设备分类
     */
    //@RequiresPermissions("system:categories:add")
    @Log(title = "设备分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RentalDeviceCategories rentalDeviceCategories)
    {
        log.info("======== 新增设备分类请求 ========");
        log.info("新增数据: {}", rentalDeviceCategories);
        
        int result = rentalDeviceCategoriesService.insertRentalDeviceCategories(rentalDeviceCategories);
        log.info("新增结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 新增设备分类完成 ========");
        return toAjax(result);
    }

    /**
     * 修改设备分类
     */
    //@RequiresPermissions("system:categories:edit")
    @Log(title = "设备分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RentalDeviceCategories rentalDeviceCategories)
    {
        log.info("======== 修改设备分类请求 ========");
        log.info("修改数据: {}", rentalDeviceCategories);
        
        int result = rentalDeviceCategoriesService.updateRentalDeviceCategories(rentalDeviceCategories);
        log.info("修改结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 修改设备分类完成 ========");
        return toAjax(result);
    }

    /**
     * 删除设备分类
     */
    //@RequiresPermissions("system:categories:remove")
    @Log(title = "设备分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{categoryIds}")
    public AjaxResult remove(@PathVariable Long[] categoryIds)
    {
        log.info("======== 删除设备分类请求 ========");
        log.info("删除分类ID列表: {}", java.util.Arrays.toString(categoryIds));
        log.info("删除数量: {} 个分类", categoryIds.length);
        
        int result = rentalDeviceCategoriesService.deleteRentalDeviceCategoriesByCategoryIds(categoryIds);
        log.info("删除结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 删除设备分类完成 ========");
        return toAjax(result);
    }
}
